//
//  HFCalendarModel.m
//  HFCalendar
//
//  Created by Luffy on 2021/8/24.
//

#import "HFCalendarModel.h"
#import "HFCalendarHelper.h"

@implementation HFCalendarModel

- (NSArray<HFCalendarModel *> *)achieveModelWithData:(NSDate *)startDate
                                              toDate:(NSDate *)endDate {
    NSMutableArray *modelArray = [@[] mutableCopy];
    HFCalendarHelper *helper = [HFCalendarHelper defaultManager];
    
    NSDateFormatter *formatter = [HFCalendarHelper createFormatterWithDateFormat:@"yyyy年MM月"];
    // 判断所给年月距离当前年月有多少个月
    NSDateComponents *components = [helper.calendar components:NSCalendarUnitMonth fromDate:startDate toDate:endDate options:NSCalendarWrapComponents];
    
    // 循环遍历得到从给定年月一直到当前年月的所有年月信息
    for (NSInteger i = 0; i<= components.month; i++) {
        NSDateComponents *monthComponents = [[NSDateComponents alloc] init];
        monthComponents.month = i;
        NSDate *headerDate = [helper.calendar dateByAddingComponents:monthComponents toDate:startDate options:0];
        NSString *headerTitle = [formatter stringFromDate:headerDate];
        
        // 获取此Section所表示月份的天数
        NSRange daysOfMonth = [helper.calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:headerDate];
        NSUInteger numberOfDaysInMonth = daysOfMonth.length;
        
        // 获取此Section所表示月份的第一天是第一个星期的第几天（当前日历的每个星期的第一天是星期日）
        NSDateComponents *comps = [helper.calendar components:NSCalendarUnitWeekday fromDate:headerDate];
        NSInteger firstDayInMonth = [comps weekday];
        
        NSInteger sectionRow = ((numberOfDaysInMonth + firstDayInMonth - 1) % 7 == 0) ? ((numberOfDaysInMonth + firstDayInMonth - 1) / 7) : ((numberOfDaysInMonth + firstDayInMonth - 1) / 7 + 1);
        
        HFCalendarModel *model = [HFCalendarModel new];
        model.numberOfDaysOfTheMonth = numberOfDaysInMonth;
        model.firstDayOfTheMonth = firstDayInMonth;
        model.headerTitle = headerTitle;
        model.sectionRow = sectionRow;
        [modelArray addObject:model];
    }
    return [modelArray copy];
}

@end
